<template>
  <div class="dynamic-item" v-if="obj">
  	<div class="header" :class="obj.page === 'service'?'header-service':''">
  		<div v-if="obj.page === 'community'" class="avatar-container margin-r">
			<img :src="obj.avatar?addPath(obj.avatar):favicon" />
		</div>
		<div class="margin-r">{{obj.name}}{{obj.shop.name}}<span v-if="obj.page === 'service'">|</span>{{obj.distance}}&nbsp;&nbsp;{{obj.shop.specialServices}}</div>
		<div v-if="obj.page !== 'community'"><i class="iconfont icon-ai45"></i></div>
		<div class="stars"><starPercent v-if="obj.shop.creditRate !== undefined" :percent="obj.shop.creditRate*20"></starPercent></div>
  	</div>
    <div v-if="!obj.images" v-tap="{methods:goActiveDetail,obj:obj}">
    	<div v-if="obj.title" class="title">{{obj.title}}</div>
    	<div class="content" v-html="contentFilter(obj.content)"></div>
    </div>
    <!-- <div v-if="obj.images && obj.images.length < 3"></div> -->
    <div v-if="obj.videos" class="video">
    	<video style="width:100%;" :src="addPath(obj.videos)" controls>
    		不支持的格式
    	</video>
    </div>
    
    <div v-if="obj.images && obj.images.length < 3" class="few-pictures" v-tap="{methods:goActiveDetail,obj:obj}"> 
    		<div class="left">
    			<div v-if="obj.title" class="title">{{obj.title}}</div>
    			<div class="content" v-html="contentFilter(obj.content)"></div>
    		</div>
    		<div v-if="obj.images[0]" class="right square">
    			<img :src="addPath(obj.images[0])" />
    		</div>
    </div>
    
    <div v-if="obj.images && obj.images.length >= 3" class="many-pictures" v-tap="{methods:goActiveDetail,obj:obj}"> 
    		<div class="image-top">
    			<div v-if="obj.title" class="title">{{obj.title}}</div>
    			<div class="content" v-html="contentFilter(obj.content)"></div>
    		</div>
    		<div class="image-bottom">
    			<div class="img-container">
    				<img :src="addPath(obj.images[0])"/>
    			</div>
    			<div class="img-container">
    				<img :src="addPath(obj.images[1])"/>
    			</div>
    			<div class="img-container hover">
    				<img :src="addPath(obj.images[2])" />
    				<div class="img-num"><div class="text">共{{obj.images.length}}张</div></div>
    			</div>
    		</div>
    </div>
    <!--start 通用footer -->
    <div class="footer">
		<div class="flex-l">
			<div class="margin-r">{{$.timeFilter(obj.time)}}{{obj.publishDate}}</div>
		</div>
		<div class="flex-r">
			<div class="iconfont icon-renyuan"></div>
			<div class="margin-r">{{obj.attendNum || 0}}</div>
			<!-- <div class="iconfont" @click="likeButton" :class="obj.isSupport ==='1'?'icon-xihuan1':'icon-kongxinxihuan'"></div> -->
			<div class="iconfont icon-gzrs"></div>
			<div class="margin-r">{{obj.followCount || 0}}</div>
			<div class="iconfont icon-fenxiang" @click="share" v-if="obj.type !== 'ad' && $.isApp && obj.page === 'service' && $.env !== 'webOrWechat'"></div>
			<div class="iconfont icon-shanchu3" v-if="!isActiveList && isShow && $.env !== 'webOrWechat'" @click="shield(obj.id,index)"></div>
		</div>
    	
    </div>
    <!--end 通用footer -->
  </div>
</template>
<script>
import defaultAvatar from "assets/icon_service.png";
import emojiService from "services/common/emoji";
import createSpaceSupport from "services/community/CreateSpaceSupport.js";
import starPercent from "components/star-percent";
import favicon from 'assets/favicon.png'
/**
 * 给请求来的富文本添加样式
 * @param {*} styles 要添加的css 样式
 * @param {*} styleId 唯一标识 防止重复创建
 */
function includeStyleElement(styles, styleId) {
  if (document.getElementById(styleId)) {
    return;
  }
  var style = document.createElement("style");
  style.id = styleId;
  (document.getElementsByTagName("head")[0] || document.body).appendChild(
    style
  );
  if (style.styleSheet) {
    style.styleSheet.cssText = styles;
  } else {
    style.appendChild(document.createTextNode(styles));
  }
}

export default {
  name: "dynamic-item",
  data() {
    return {
      defaultAvatar,
      route_name: {
        product: "product",
        vr: "banner_vr",
        ad: "advertisement",
        activity: [
          "eve_robRedPacket",
          "eve_shakes",
          "eve_luckyDraw_two",
          "eve_groupShopping",
          "eve_robBuy",
          "eve_timeSpike",
          "eve_helpBargain",
          "eve_recommend"
        ],
        article: "like_car",
        promotion: "promotion-info"
      },
      favicon
    };
  }, // 截取日期字符串
  components: {
    starPercent
  },

  computed: {},
  watch: {},
  props: {
    isShow: {
      default() {
        return true;
      }
    },
    obj: {
      required: true
    },
    index: {
      default() {
        return 0;
      }
    },
    isActiveList: false,
    isTopic: false
  },
  created() {
    //	console.log('dynamic')
    console.log(this.$.env)
  },
  methods: {
    //屏蔽
    shield(id, index) {
      if (!this.$.userId) {
        this.$.goLogin({
          name: "login"
        });
        return;
      }
      let params = {
        id: id,
        index: index
      };
      this.$emit("shield", params);
    },
    goActiveDetail(params) {
      console.log(params.obj);

      let _obj = this.obj;
      if (
        this.isTopic ||
        _obj.postType == "riders" ||
        _obj.postType == "fleet"
      ) {
        //		   console.log(params)
        this.$router.push({
          name: "new_comment_detail",
          query: {
            id: _obj.id,
            refId: _obj.refId
          }
        });
        return
      } else if (_obj.postType == "topic") {
        this.$router.push({
          name: "new_topic_detail",
          query: {
            topicId: _obj.refId,
            topicTit: _obj.content
          }
        });
        return
      } else if (_obj.postType == "activity") {
        this.$router.push({
          name: "activity_list_detail",
          query: {
            activeId: _obj.refId
          }
        });
        return
      }

      if (params.obj.type === "promotion") {
        if (params.obj.promotion.type === "1") {
          this.$router.push({
            name: "cb_couponInfo",
            query: {
              id: params.obj.promotion.id,
              isGet:true
            }
          });
          return;
        }
        this.$router.push({
          name: "promotion-info",
          meta: {
            title: "促销详情",
            auth: true
          },
          params: {
            id: params.obj.forum_type.id,
            linkName: "sales-promotion"
          }
        });
      } else if (params.obj.type === "activity") {
        this.$router.push({
          name: this.route_name[params.obj.type][params.obj.forum_type.type],
          params: {
            activityId: params.obj.forum_type.id,
            title: params.obj.forum_type.title
          }
        });
      } else if (params.obj.type === "vr") {
        console.log(params.obj);
        this.$router.push({
          name: "banner_vr",
          query: {
            shop: params.obj.forum_type.filePath
          }
        });
      } else if(params.obj.type === "article"){
        this.$router.push({
          name: this.route_name[params.obj.type],
          query: {
            id: params.obj.article.id,
          }
        });
      }else{
        this.$router.push({
          name: this.route_name[params.obj.type],
          query: {
            id: params.obj.id,
            title: params.obj.title,
            url: params.obj.forum_type.path ? params.obj.forum_type.path : ""
          }
        });
      }
    },
    abc() {
      console.log("1111111111111111111");
    },
    contentFilter(content) {
      // test
      // content = "[:D]123[<//>]123awedasdasd";
      //   if(content){
      // 	  content = content.split('<p>')[1] && content.split('<p>')[1].split('</p>')[0] || ''
      //   }
      if (content) {
        for (let key in emojiService.EMOJI_MAP) {
          while (content.indexOf(key) !== -1) {
            content = content.replace(key, function() {
              let src = emojiService.getEmojiSrc(key);
              return `<img width=22 src="${src}">`;
            });
          }
        }
        let indexStart = 0; // 记录查找位置
        let indexEnd = 0;
        let flag = true;
        let oldTopicTitle = [];
        // while(flag){
        // 	if(content.indexOf('#',indexEnd+1) == -1){
        // 		// console.log('indexStart: '+ indexStart)
        // 		// console.log('indexEnd: '+ indexEnd)
        // 		flag = false
        // 	}else{
        indexStart = content.indexOf("#", indexStart);
        indexEnd = content.indexOf("#", indexStart + 1);
        //				console.log('indexEnd: '+ indexEnd)
        let topicTitle = content.slice(indexStart, indexEnd + 1) || "";
        if (oldTopicTitle.indexOf(topicTitle) === -1) {
          oldTopicTitle.push(topicTitle);
          this.obj.topics &&
            this.obj.topics.forEach(res => {
              if (`#${res.content}#` === topicTitle) {
                content = content
                  .split(topicTitle)
                  .join(`<span class="topicTitle">${topicTitle}</span>`);
              }
            });
          // 	}

          // }
        }
        this.$nextTick(() => {
          let topicTitle = ".content .topicTitle{color:#1f99e4}";
          includeStyleElement(topicTitle, "topicTitle");
        });
      }
      return content;
    },
    //	deleteItem(){
    //		console.log(this.index)
    //
    //			CreatePostBlacklist.bind(this)({
    //				id:this.obj.id
    //			},resp=>{
    //				this.$emit('deleteItem',this.index)
    //			})
    //
    //
    //	},
    likeButton() {
      createSpaceSupport.bind(this)(
        {
          spaceId: this.obj.id
        },
        resp => {
          //			console.log(resp)
          this.obj.isSupport = this.obj.isSupport == "1" ? "0" : "1";
        }
      );
    },
    //分享
    share() {
      let shareThumImage = "/upload/image/default_user_icon.png";
      let url;
      let content;
      let itemArr = this.obj;
      let type = '9'
      let id = ''
      console.log(itemArr);
      switch (itemArr.type) {
        case "activity":
          content = "活动好精彩快来参加吧!";
          id = itemArr.marketing.id;
          switch (itemArr.marketing.type) {
            case "0":
              url = this.$.host + "/eve_robRedPacket/" + itemArr.marketing.id;
              break;
            case "1":
              url = this.$.host + "/eve_shakes/" + itemArr.marketing.id;
              break;
            case "2":
              this.$.get({
                methodName: "LotteryInitInfo",
                category: "2",
                id: itemArr.marketing.id
              }).then(res => {
                console.log(res);
                if (res.data.shape === "0") {
                  url =this.$.host + "/eve_luckyDraw_two/" + itemArr.marketing.id;
                } else {
                  url = this.$.host + "/eve_luckyDraw/" + itemArr.marketing.id;
                }
                this.$.push("route_share", {
                  shareTitle: itemArr.title,
                  shareContent: content,
                  shareThumImage: shareThumImage,
                  shareType: type,
                  needOAuth: "0",
                  shareUrl: url,
                  shareId: id
                });
              });
              break;
            case "3":
              url = this.$.host + "/eve_groupShopping/" + itemArr.marketing.id;
              break;
            case "4":
              url = this.$.host + "/eve_robBuy/" + itemArr.marketing.id;
            case "5":
              url = this.$.host + "/eve_timeSpike/" + itemArr.marketing.id;
              break;
            case "6":
              url = this.$.host + "/eve_helpBargain/" + itemArr.marketing.id;
            case "7":
              url = this.$.host + "/eve_recommend/" + itemArr.marketing.id;
              break;
          }
          break;
        case "promotion":
          content = "我在V服有大发现，绝对适合你，速来围观!";
          url = this.$.host + "/promotion-info/" + itemArr.promotion.id;
          break;
        case "vr":
              this.$.push('route_share', {
								shareTitle: '展厅',
								shareContent: '360度，不一样的展厅~',
								shareThumImage:'/upload/image/default_user_icon.png',
								shareType: '14',
								needOAuth: '0',
								shareUrl: itemArr.vr.filePath + '/index.html',
								shareId: ''
              })
              return;
          break;
        case "article":
          type = '1'
          content = "摘要";
          id = itemArr.article.id
          url = this.$.host + "/like_car?id=" + itemArr.article.id;
          break;
        case "product":
          type = '20'
          console.log(itemArr);
          id = itemArr.id
          url = this.$.host + "/product?id=" + itemArr.id;
          break;
      }
      if(url){
        this.$.push("route_share", {
          shareTitle: itemArr.title,
          shareContent: content,
          shareThumImage: shareThumImage,
          shareType: type,
          needOAuth: "0",
          shareUrl: url,
          shareId: id
        });
      }
    }
  }
};
</script>

<style scoped>
.dynamic-item {
  padding: 1em;
  border-bottom: 1px solid #ececec;
}
.icon-ai45 {
  color: #f98700;
}
.title {
  font-weight: bolder;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-top: 1em;
  height: 16px;
  line-height: 16px;
}
.content {
  margin-top: 1em;
  line-height: 16px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
.content .topicTitle {
  color: skyblue;
}
.header {
  display: flex;
  align-items: center;
}
.header-service {
  justify-content: space-between;
  padding: 10px 0;
}
.footer {
  display: flex;
  margin-top: 1em;
  align-items: center;
  color: #666;
  justify-content: space-between;
}
.footer .flex-l {
  display: flex;
  margin-top: 1em;
  align-items: center;
  color: #666;
}
.footer .flex-r {
  display: flex;
  margin-top: 1em;
  align-items: center;
  color: #666;
}
.avatar-container {
  width: 2em;
  height: 2em;
}
.icon-container {
  width: 18px;
  height: 18px;
}
.icon-container img,
.avatar-container img {
  width: 100%;
  object-fit: cover;
}
.margin-r {
  margin-right: 15px;
}
.icon-fenxiang {
  margin-right: 15px !important;
}
.video {
	width:100%;
	height:50vw;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
  border:1px solid #ececec;
}
.video video {
	width:100%;
	height:100%;
}
.few-pictures {
  display: flex;
}
.left {
  flex: 2 1 0;
  display: flex;
  flex-flow: column;
  justify-content: center;
  padding-right: 10px;
  overflow: hidden;
}
.right {
  flex: 1 1 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.right img {
  width: 90%;
  height: 27vw;
  object-fit: cover;
}
.image-bottom {
  width: calc(100% - 1em);
  display: flex;
  margin: 0 auto;
}
.image-bottom .img-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1 1 0;
}
.img-container img {
  width: 90%;
  height: 27vw;
  object-fit: cover;
}
.footer .iconfont {
  font-size: 16px;
  margin: 0 5px 0 3px;
  color: #666;
}
.hover {
  position: relative;
}
.img-num {
  position: absolute;
  bottom: 0;
  right: 5%;
}
.text {
  padding: 6px;
  font-size: 10px;
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
}

/*推荐相关*/
.stars {
}
.stars .star-percent {
  /*font-size:12px;*/
}
</style>